<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

class PublicController extends Controller
{
    public function __construct(\think\Request $request = null)
    {
        parent::__construct();

        session_start();
    }

    public function login(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $name = input('name');
            $password = input('password');

            $user = Db::name('users')->where('name', $name)->find();
            if($user['password'] == $this->encode_password($password)){
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user'] = $user;
                $this->success('Login success!', 'index/index/index');
            }else{
                $this->error('Wrong account or password!');
            }
        }

        return $this->fetch();
    }

    public function check_in(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $invitation_code = input('invitation_code');
            $password = input('password');

            $reservation = Db::name('reservation')->where('invitation_code', $invitation_code)->find();

            if(!$reservation){
                $this->error('Wrong invitation code or password!');
            }

            if($reservation['status'] == 'Verified'){
                $this->error('Each code can be validated for only once!');
            }

            $user = Db::name('users')->where('id', $reservation['user_id'])->find();
            if($user['password'] == $this->encode_password($password)){
                $reservation = Db::name('reservation')
                    ->where('invitation_code', $invitation_code)
                    ->update(['status'=>'Verified']);
                $this->success('Welcome, '.$user['name'].'!', 'check_in', [], 5);
            }else{
                $this->error('Wrong invitation code or password!');
            }
        }

        return $this->fetch();
    }

    public function register(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $name = input('name');
            $post_data = input('post.');
            $post_data['password'] = $this->encode_password($post_data['password']);
            //先查已有用户
            $user = Db::name('users')->where('name', $name)->find();
            if(!empty($user)){
                $this->error('User name already exists ');
            }

            $auth = Db::name('users')->insertGetId($post_data);

            if($auth){
                $this->success('success!', 'login');
            }else{
                $this->error('error');
            }
        }

        return $this->fetch();
    }


    public function encode_password($password){
        return md5($password.'li20210520');
    }

    public function logout(){
        $_SESSION = [];
        $this->success('success!', 'login');
    }
}
